
import { getGoodsDetail, addCart, getGoodsCoupon, getCartNum ,getCommentList,querycommentsummarize,getBestList} from '../../api/store'
import { collectGoods ,cancelattention} from '../../api/user'
import { trottle, Tips, getUrlParams } from '../../utils/util'
import { showLoginDialog, getRect } from '../../utils/wxutil'
import wxParse from '../../wxParse/wxParse'
import { CollectType } from '../../utils/type'
import event from './../../utils/events'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        showSpec: false,
        showCoupons: false,
        popupType: '',
        swiperList: [],
        goodsDetail: {},
        goodsLike: [],
        comment: {},
        headImg:'',
        commentList: [],
        checkedGoods: {},
        couponList: [],
        isFirstLoading: true,
        isCollect: CollectType.CANCEL_COLLECTION,
        timeData: {},
        // 动画数据
        actionData: {},
        shopCartActionData: {},
        cartNum: "",
        emptyDetail: false
    },

    // 收藏商品
    collectGoods(e) {
        this.$handleCollectGoods({  skuId: this.data.goodsDetail.id });
    },

    $handleCollectGoods(data) {
        let { $state: {isLogin} }  = this.data
        if (!isLogin) {
            showLoginDialog()
            return
        }
        if(this.data.goodsDetail.hasAtten){
             cancelattention(data).then(res => {
                    if (res.code == 200) {
                        Tips({title: "取消收藏"})
                        event.emit("REFLASH");
                        this.$getGoodsDetail();
                    }
                })
        }else{
            collectGoods(data).then(res => {
                        if (res.code == 200) {
                           Tips({title: "收藏成功"})
                            event.emit("REFLASH");
                            this.$getGoodsDetail();
                        }
                    })
        }

    },

    async onLoadFun() {
        this.$getGoodsDetail()
this.$getCommentList()
this.$querycommentsummarize()
        this.$getCartNum()

    },
    $getCartNum() {
        let { $state: {isLogin} }  = this.data
        if (!isLogin) {
            return
        }
        getCartNum().then(res => {

            if(res.code == 200) {
                this.setData({
                    cartNum: res.data
                })
            }
        })
    },
 $getCommentList() {
            getCommentList(this.id).then(res => {
                if(res.code == 200) {
                    this.setData({
                        commentList: res.data.list
                    })
                }
            })
    },
     $querycommentsummarize() {
                querycommentsummarize(this.id).then(res => {
                    if(res.code == 200) {
                        this.setData({
                            comment: res.data
                        })
                    }
                })
        },
    $getGoodsDetail() {
            getGoodsDetail({
                goodsId: this.id
            }).then(res => {
                if (res.code == 200) {
                    let { images, mobileDesc, marketings,  like,coupons } = res.data
                    this.setData({
                        goodsDetail: res.data,
                        swiperList: images,
                        couponList:coupons,
                        isFirstLoading: false
                    })
                    getBestList({

                                    secondCateId:res.data.spu.secondCateId,
                                     pageNum: 0
                                    }).then(res => {
                                            if(res.code == 200) {
                                                this.setData({
                                                    goodsLike: res.data.list
                                                })
                                            }
                                        })
                    wx.nextTick(() => {
                        getRect('.cart').then(res => {
                            this.cartLeft = res.left + res.width/2
                            this.cartTop = res.top - res.height
                
                        })
                    })
                    if(mobileDesc){
                      wxParse.wxParse('content', 'html', mobileDesc, this, 10);
                    }else{
                     wxParse.wxParse('content', 'html', '无详情', this, 10);
                    }

                }else {
                    this.setData({
                        emptyDetail: true
                    })
                }
            })
    },
   
    onChangeSpec(e) {
    console.log(e.detail)
        this.setData({
            checkedGoods: e.detail
        })
    },
    onShowCoupons(e) {
        let { $state: {isLogin} }  = this.data
        if (!isLogin) {
            showLoginDialog()
            return
        }
        this.setData({
            showCoupons: true
        })
    },
   onShareTap() {
           const self = this;
           if (_g.checkLogin({
               type: 1
           })) {
               if (!self.poster.data.canvasUrl) {
                  _g.toast({
                      title: '海报未生成，请稍后重试',
                      duration: 2000
                  });
                  return;
               }
               self.setData({
                   hideShareDialog: false
               });
           } else {
               _g.toast({
                   title: '请先登录'
               })
           }
       },
    getShareCode() {
               const self = this;
               let userInfo = wx.getStorageSync('userInfo');
               if (!userInfo) return;
               let sence = 'p=' + userInfo.selfRecommendCode;
               sence += '&id=' + self.data.goodsDetail.id;
               //sence += '&t=' + self.data.thirdId;
             //
               let path = '';
               if (!self.data.userCutId) {
                   path = 'pages/goods/detail';
               } else {
                   path = 'pages/goods/bargain';
               }
               Platform.getShareQR(self, {
                   scene: sence,
                   page: path
               }).then((ret) => {
                   self.downloadImg({
                       imgUrl: _g.getImageUrl(ret.data.shareQR)
                   }, (res) => {
                       self.setData({
                           shareCode: res
                       });
                       self.checkDownload();
                   },2);

               }, (err) => {

               });
           },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if(options.scene) {
            let scene = getUrlParams(decodeURIComponent(options.scene))
            options.id = scene.id
        }
        if (options && options.recommondCode) {
        			wx.setStorageSync('recommondCode', options.recommondCode)
        		}
        this.actionObj = wx.createAnimation({
            duration: 1000,
            delay: 0,
            timingFunction: "linear"
        });
        this.cartActionObj = wx.createAnimation({
          delay: 0,
          duration: 100,
          timingFunction: "ease-in-out"
        })
        this.onAddCart = trottle(this.onAddCart, 800, this)
        this.id = options.id
        this.onLoadFun()
    },
    goPage(e) {
        let { url } = e.currentTarget.dataset
        wx.navigateTo({
            url
        })
    },
  
    showSpec(e) {
        let { $state: {isLogin} }  = this.data
        if (!isLogin) {
            showLoginDialog()
            return
        }
        let { type } = e.currentTarget.dataset
        this.setData({
            popupType: type,
            showSpec: true
        })
    },
    onClose() {
        this.setData({
            showSpec: false,
            showCoupons: false
        })
    },
    onAddCart(e) {
    console.log(e.detail)
        let { id, goodsNum } = e.detail
        addCart({
            skuId: id,
                                    spuId: this.data.goodsDetail.spu.id,
            num: goodsNum
        }).then((res) => {
            if (res.code == 200) {
                this.setData({
                    showSpec: false
                })
                // wx.showToast({ title: res.msg })
                this.runGoodsAnim();
                // this.$getCartNum()
            }
        })
    },
    onBuyNow(e) {

        let { id, goodsNum } = e.detail

         const data = {};
        this.setData({
            showSpec: false
        })
        data.ids = '';
                				data.isGroup = 0;
                				data.skuInfo = id + ',' + goodsNum;
                				data.groupId = 0;
        wx.nextTick(() => {
            wx.navigateTo({
                url: `/pages/confirm_order/confirm_order?goods=${JSON.stringify(data)}`
            })
        })
    },

    // 创建动画实例
    runGoodsAnim: function(callback) {
      
        this.initAnim();
        // 缩放动画
        this.actionObj.opacity(1).scale(0.35).step({duration: 300,});
        // 曲线动画
        this.actionObj.left(80).step({duration: 200, timingFunction: "ease-out" })
        this.actionObj.top(this.cartTop * 1 / 2).opacity(0.8).step({duration: 200, delay: 0, timingFunction: "linear"})
        this.actionObj.left(this.cartLeft).step({duration: 200, timingFunction: "ease-in"})
        this.actionObj.top(this.cartTop).opacity(0).scale(0).step({duration: 200,delay: 0,timingFunction: "linear" });
        this.cartActionObj.rotate(15).step({delay: 1000,});
        this.cartActionObj.rotate(-15).step();
        this.cartActionObj.rotate(15).step({duration: 100});
        this.cartActionObj.rotate(-15).step({duration: 100});
        this.cartActionObj.rotate(0).step()
      
        this.setData({
            actionData: this.actionObj.export(),
            cartActionObj: this.cartActionObj.export()
        });
        setTimeout(() => {
            this.$getCartNum()
        },1000)
        
    },

    initAnim: function() {
        this.actionObj.translateX('-50%')
                      .translateY(0)
                      .top('2%')
                      .left('50%')
                      .opacity(0)
                      .scale(1)
                      .step({duration: 0});
        this.setData({
            actionData: this.actionObj.export(),
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: async function () {
        
        
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: async function () {
             let userInfo = wx.getStorageSync("userInfo")
            if(userInfo) {
                return {

                    path: "pages/product/product?recommondCode="+userInfo.selfRecommendCode
                }
            } else {
                return {
                    path: "pages/product/product"
                }
            }
        }
    
})